package com.tianbao54.concurrent.countdownlatch;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class CountDownLatchTest {

    public static void main(String[] args) {

        ExecutorService service = Executors.newFixedThreadPool(4);
        CountDownLatch countDownLatch = new CountDownLatch(3);

        service.submit(new Worker("zhangsan",countDownLatch));
        service.submit(new Worker("lisi",countDownLatch));
        service.submit(new Worker("wangwu",countDownLatch));

        service.submit(new Boss(countDownLatch));

        service.shutdown();
    }

    static class Worker implements Runnable {

        private String name;
        private CountDownLatch countDownLatch;

        Worker (String name,CountDownLatch countDownLatch) {
            this.name = name;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            doWork();
            this.countDownLatch.countDown();
        }

        private void doWork () {
            System.out.println(name + " 正在干活.");
            try {
                TimeUnit.SECONDS.sleep(new Random().nextInt(10));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name + " 已经干完活了.");
        }
    }

    static class Boss implements Runnable {

        private CountDownLatch countDownLatch;

        Boss (CountDownLatch countDownLatch) {
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            await();
        }

        public void await () {
            System.out.println("老板正在等员工把活干完.");
            try {
                this.countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("所有的员工已经干完活了，老板验收工作.");
        }
    }
}